<template>
  <section class="details-box">
    <div class="no_derate" v-if="isNoDerate">
      <div class="color-g">{{isDisabled?'无减免项,缴费项目开始后,不可添加':'暂无减免项'}}</div>
      <el-button v-if="!isDisabled" icon="document" size="large" type="primary" @click="setDerate" style="margin-top:20px">新增减免项</el-button>
    </div>
    <div class="content-top" v-if="derateArr.length">
      <div class="content-title"><span style="color:#999">缴费名称：</span>{{projectInfo.name}}</div>
      <div class="content-title"><span style="color:#999">缴费金额：</span>{{projectAmount}}</div>
    </div>
    <div class="middle" v-if="derateArr.length">
      <el-table :data="derateArr" ref="derateTable" tooltip-effect="dark" style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="65">
        </el-table-column>
        <el-table-column prop="reason" label="减免原因">
          <template slot-scope="scope">
            <el-input  v-model="scope.row.reason" :disabled="isDisabled||scope.row.isDisabled" :maxlength="20"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="减免金额(元/学生)">
          <template slot-scope="scope">
            <el-input v-model="scope.row.num" :disabled="isDisabled||scope.row.isDisabled"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="" label="减免学生">
          <template slot-scope="scope">
            <el-button type="text" @click="setDerateStudent(scope)" v-if="!scope.row.studentIds.length">选择参与学生</el-button>
            <span v-if="scope.row.studentIds.length" >共选择{{getStudentCount(scope.row.studentIds)}}人</span>
            <el-button v-if="scope.row.studentIds.length" type="text" @click="setDerateStudent(scope)" class="eye"></el-button>
          </template>
        </el-table-column>
        <el-table-column prop="show" label="是否显示在缴费页面">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.show" :disabled="isDisabled||scope.row.isDisabled"></el-checkbox>{{scope.row.show?' 显示':''}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="editDerate(scope)" type="text" size="small" v-if="scope.row.id&&scope.row.isDisabled" :disabled="isDisabled">编辑</el-button>
            <el-button @click="delDerate(scope)" type="text" size="small" :disabled="isDisabled">删除</el-button>
            <el-button @click="btnDerate(scope)" type="text" size="small" :disabled="isDisabled" v-if="!scope.row.id||!scope.row.isDisabled">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="text" @click="setDerate" :disabled="isDisabled">+添加减免</el-button>
    </div>
    <el-dialog :visible.sync="derateVisible" v-bind:close-on-click-modal='false' :before-close="handleDerateClose" custom-class="modelClass">
      <span slot="title">选择减免学生</span>
      <el-input
        placeholder="输入关键字进行搜索"
        v-model="filterText">
      </el-input>
      <el-tree v-if="derateVisible" :data="studentList" show-checkbox="" node-key="id" :default-checked-keys="derateArr[this.itemIndex].studentIds" ref="derateTree" highlight-current :props="defaultProps" :filter-node-method="filterNode"></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getDerateStudent" class='bottom' :disabled="isDisabled">保存</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import {modifyProject, getStudentsList, setDiscount, updateDiscount, deleteDiscount, editStudentDiscount, getDiscountList, getDiscount} from 'api/school/project/index'
import common from 'src/util/common'
let arr = [] // 临时存储的选择学生
export default {
  data () {
    return {
      schoolPaymentSkuId: parseInt(common.params('id')), // 缴费项目id
      derateArr: [], // 减免项
      derateVisible: false, // 选择学生弹框
      studentList: [], // 选择班级的所有学生列表
      itemIndex: 0, // 选择的第几项减免项
      isDisabled: false, // 是否禁止修改数据
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      projectInfo: {}, // 缴费项目信息
      projectAmount: '', // 项目金额
      isNoDerate: false, // 是否显示空白页
      filterText: '' // 关键字搜索
    }
  },
  created () {
    this.getData()
  },
  methods: {
    getData () { // 获取项目详情
      modifyProject({id: this.schoolPaymentSkuId}).then(res => {
        if (new Date(res.data.startTime * 1000) < new Date()) {
          this.isDisabled = true
        }
        this.projectInfo = res.data
        this.projectAmount = (res.data.amount / 100).toFixed(2)
        getStudentsList({classId: res.data.classList}).then(v => {
          this.studentList = v.data
          if (this.isDisabled) {
            this.studentList.forEach(v => {
              v.disabled = true
              v.children.forEach(vv => {
                vv.disabled = true
              })
            })
          }
        })
        getDiscountList({id: this.schoolPaymentSkuId}).then(res => {
          res.data.forEach(v => {
            v.show = parseInt(v.show) === 1
            v.isDisabled = true
            v.num = (v.num / 100).toFixed(2)
          })
          this.derateArr = res.data
        })
      })
    },
    setDerate () { // 点击设置减免项
      for (let v of this.derateArr) {
        if (!v.id) {
          return this.$message({
            type: 'error',
            message: '请保存上一条减免信息后在继续添加'
          })
        }
      }
      if (this.derateArr.length === 10) {
        return this.$message({
          type: 'error',
          message: '最多添加10个减免项'
        })
      }
      this.derateArr.push({reason: '', num: '', show: true, offType: 1, studentIds: [], errText: ''})
    },
    setDerateStudent (obj) { // 点击选择减免学生
      this.derateVisible = true
      this.itemIndex = obj.$index
    },
    delDerate (obj) { // 删除减免项
      let index = obj.$index
      let id = obj.row.id
      if (id && !this.isDisabled) { // 优惠项id存在则为编辑模式
        this.$confirm('此操作将永久删除改减免项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteDiscount({id: id}).then(v => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.derateArr.splice(index, 1)
          })
        }).catch(() => {})
      } else {
        this.derateArr.splice(index, 1)
      }
    },
    editDerate (obj) { // 编辑减免项
      let index = obj.$index
      this.derateArr[index].isDisabled = false
    },
    btnDerate (obj) { // 保存减免项
      let tmpObj = obj.row
      let result = this.derateRule(tmpObj)
      if (!result.flag) {
        return this.$message({
          type: 'error',
          message: `第${obj.$index + 1}行${result.errText}`
        })
      }
      let index = obj.$index
      if (tmpObj.id) { // 更新操作
        updateDiscount({
          id: tmpObj.id,
          reason: tmpObj.reason,
          show: tmpObj.show ? 1 : 2,
          num: common.mul(tmpObj.num, 100)
        }).then(v => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.derateArr[index].isDisabled = true
        })
      } else { // 添加减免项操作
        // if (!tmpObj.studentIds.length) {
        //   return this.$message({
        //     type: 'error',
        //     message: '至少选择一个学生'
        //   })
        // }
        setDiscount({
          schoolPaymentSkuId: this.schoolPaymentSkuId,
          reason: tmpObj.reason,
          num: common.mul(tmpObj.num, 100),
          show: tmpObj.show ? 1 : 2,
          offType: 1,
          studentIds: tmpObj.studentIds
        }).then(v => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.derateArr[index].isDisabled = true
          this.derateArr[index].id = v.data.discountId
          this.getDerate(this.derateArr[index], this.derateArr[index].id, 2) // 更新成功重新拉取该项减免信息
        })
      }
    },
    getDerateStudent () { // 学生选择弹窗保存
      let item = this.derateArr[this.itemIndex]
      arr = this.$refs.derateTree.getCheckedKeys()
      // if (!arr.length) {
      //   return this.$message({
      //     type: 'error',
      //     message: '至少选择一个学生'
      //   })
      // }
      if (!item.id) {
        item.studentIds = arr
        this.derateVisible = false
      } else {
        let addIds = arr.concat(item.studentIds).filter(v => !item.studentIds.includes(v))
        let delIds = arr.concat(item.studentIds).filter(v => !arr.includes(v))
        editStudentDiscount({
          discountId: item.id,
          addIds,
          delIds
        }).then(v => {
          this.$message({
            type: 'success',
            message: '保存学生成功!'
          })
          this.getDerate(item, item.id) // 更新成功重新拉取该项减免信息
        })
      }
    },
    derateRule (v) { // 减免规则校验
      let flag = true // 是否通过减免验证
      let errText = ''
      if (!v.reason) {
        errText = '减免原因不能为空。 '
        flag = false
      }
      if (!(/^\d+(.\d{1,2})?$/.test(v.num))) {
        errText += `减免金额格式不正确,请输入0.01到${this.projectAmount}之间的数字(最多两位小数)。 `
        flag = false
      } else if (Number(v.num) >= parseInt(this.projectInfo.amount) || Number(v.num) < 0.01 || v.num === Infinity) {
        errText += `减免金额有误,请输入0.01到${this.projectAmount}之间的数字(最多两位小数)。 `
        flag = false
      }
      if (!v.studentIds.length) {
        errText += '至少选择一名学生参与减免。 '
        flag = false
      }
      errText = errText.slice(0, -2)
      return {flag, errText}
    },
    handleDerateClose () {
      this.derateVisible = false
    },
    getDerate (item, id, flag) { // 根据discountid 获取减免项
      getDiscount({id: [id]}).then(v => { // 更新成功重新拉取该项减免信息
        item.studentIds = v.data[0].studentIds
        item.reason = v.data[0].reason
        item.num = (v.data[0].num / 100).toFixed(2)
        item.show = v.data[0].show === 1
        if (flag === 2) {
          this.derateArr = JSON.parse(JSON.stringify(this.derateArr))
        } else {
          this.derateVisible = false
        }
      })
    },
    getStudentCount (ids) {
      let num = 0
      this.studentList.forEach(v => {
        v.children.forEach(vv => {
          if (ids.includes(vv.id)) {
            num++
          }
        })
      })
      return num
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
  },
  watch: {
    derateArr: {
      handler () {
        if (this.derateArr.length) {
          this.isNoDerate = false
        } else {
          this.isNoDerate = true
        }
      },
      deep: true
    },
    filterText (val) {
      this.$refs.derateTree.filter(val)
    }
  }
}
</script>
<style lang="less">
  .details-box {height: 100%; padding: 20px 10px;}
  .details-box .float-r{float: right;}
  .details-box .float-l{float: left;}
  .details-box .content-top{ clear: both; border-bottom: 1px solid #e1e1e1;padding: 20px 10px;}
  .details-box .middle{padding: 10px 20px;}
  .details-box .content-middle{clear: both;}
  .details-box .item{padding: 16px 0; margin-bottom: 22px; font-size: 14px; color: #48576a;}
  .details-box .name{display: inline-block; text-align: left; padding-right: 12px;}
  .details-box .content-middle .input-name{width: 300px;}
  .details-box .save{margin-top: 60px; width: 200px;}
  .details-box .red{color: red; font-size: 12px;}
  .details-box  .buttonName{position: absolute;top: 2px;height: 34px;}
  .details-box  .buttonTrue{left: 320px;}
  .details-box  .modelClass {width: 700px;}
  .details-box  .modelClass .el-dialog__header{background-color: #457ed8;padding-bottom: 16px;color: #ffffff;}
  .details-box  .modelClass .el-dialog__headerbtn .el-dialog__close{color: #ffffff;}
  .details-box  .modelClass .dialog-footer{text-align: center;}
  .details-box  .modelClass .el-checkbox{float: right;margin-right: 30px; }
  .details-box  .modelClass .bottom{width: 100px;}
  .details-box  .modelClass .el-dialog__body .el-tree--highlight-current{overflow-y: overlay; max-height: 700px; min-height: 400px;}
  .color-g { color: #999;}
  .wenhao {
    display: inline-block;
    height: 20px;
    width: 20px;
    line-height: 20px;
    text-align: center;
    border: 1px solid #ccc;
    border-radius: 50%;
  }
  .el-tooltip.item {
    padding: 0;
  }
  .flex_div {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 900px;
  }
  .flex_1 {
    width: 200px;
  }
  .flex_item {
    flex: 1;
  }
  .eye {
    width: 20px;
    height: 20px;
    padding: 0;
    background: url('../../../assets/img/eye.png') round;
    vertical-align: middle;
  }
  .mr10 {
    margin-right: 10px;
  }
  .no_derate {
    margin-top: 300px;
    text-align: center;
  }
</style>